import { observable, reaction, action } from 'mobx';
import V4 from 'uuid/v4';

class Item {
  store;
  id;
  @observable title;
  @observable done;

  constructor(store, id, title, done = false) {
    this.store = store;
    this.id = id;
    this.title = title;
    this.done = done;
  }

  @action.bound
  toggle() {
    this.done = !this.done;
  }

  @action.bound
  remove() {
    this.store.list.remove(this);
  }

  toJS() {
    return Object.keys(this).filter(key => key !== 'store').reduce((obj, key) => {
      obj[key] = this[key];
      return obj;
    }, {});
  }

  static fromJS(store, item) {
    return new Item(store, item.id, item.title, item.done);
  }
}

export default class Store {
  @observable list = [];

  storeToLocalStorage() {
    reaction(() => this.toJS(), list => localStorage.setItem('store-test-list', JSON.stringify(list)));
  }

  @action.bound
  addItem(title) {
    this.list.push(new Item(this, V4(), title, false));
  }

  toJS() {
    return this.list.map(item => item.toJS());
  }

  static fromJS(list) {
    const store = new Store();
    store.list = list.map(item => Item.fromJS(store, item));
    return store;
  }
}